<template>
  <div class="tag-selector">
    <div class="input-group">
      <a-select v-model:value="inputValue" :placeholder="placeholder" allowClear @select="handleSelect">
        <a-select-option v-for="item in options" :key="item.id" :value="item.id">
          {{ item.name }}
        </a-select-option>
      </a-select>
      <a-button type="primary" @click="handleAdd">
        <template #icon><plus-outlined /></template>
      </a-button>
    </div>
    <div class="tag-list">
      <a-tag v-for="(tag, index) in tags" :key="tag" closable @close="handleRemove(index)">
        {{ tag }}
      </a-tag>
    </div>
  </div>
</template>

<script setup lang="ts">
  import PlusOutlined from '@ant-design/icons-vue/lib/icons/PlusOutlined'
  import { computed } from 'vue'

  const props = defineProps<{
    tags: string[]
    options: InformationTypes.IDictResponse['values']
    placeholder?: string
    input?: number
  }>()

  const emit = defineEmits<{
    (e: 'update:tags', tags: InformationTypes.IDictResponse['values']): void
    (e: 'update:input', value: number | undefined): void
    (e: 'add', tag: InformationTypes.IDictResponse['values'][0]): void
    (e: 'remove', index: number): void
  }>()

  const inputValue = computed({
    get: () => props.input,
    set: (value) => emit('update:input', value),
  })

  const handleSelect = (value: number) => {
    inputValue.value = value
  }

  const handleAdd = () => {
    if (inputValue.value) {
      const selectedTag = props.options.find((t) => t.id === inputValue.value)
      if (selectedTag) {
        emit('add', selectedTag)
        inputValue.value = undefined
      }
    }
  }

  const handleRemove = (index: number) => {
    emit('remove', index)
  }
</script>

<style lang="less" scoped>
  .tag-selector {
    .input-group {
      display: flex;
      gap: 8px;

      .ant-select {
        flex: 1;
      }
    }

    .tag-list {
      margin-top: 8px;

      .ant-tag {
        margin-bottom: 8px;
      }
    }
  }
</style>
